package com.rh.mybatisstudy.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rh.mybatisstudy.model.Article;
import com.rh.mybatisstudy.realm.ShiroDbRealm;
import com.rh.mybatisstudy.service.IUserService;
import com.rh.mybatisstudy.util.CipherUtil;

@Controller
@RequestMapping("/person")
public class PersonController {
	private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/listall.do")
	public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){
		System.out.println("PersonController listall===============================");
        List<Article> articles = userService.getUserArticlesByID(1);
        ModelAndView mav = new ModelAndView("result");
        mav.addObject("articles",articles);
        return mav;
    }
	
	/**
	 * 登录示例
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request) {
		System.out.println("PersonController login");
		String result = "login";
		// 此处默认有值
		String username = request.getParameter("username");
		System.out.println("--------------------" + CipherUtil.generatePassword(request.getParameter("password")));
		//MD5加密
		String password = CipherUtil.generatePassword(request.getParameter("password"));
		//String password = request.getParameter("password");
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		
		Subject currentUser = SecurityUtils.getSubject();
		try {
			System.out.println("----------------------------");
			if (!currentUser.isAuthenticated()){
				token.setRememberMe(true);
				currentUser.login(token);
			}
			System.out.println("result: " + result);
			result = "index";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			result = "login";
		}
		return result;
	}
}
